<?php
namespace app\task\job;

use app\model\AdminStaff;
use think\queue\Job;
use think\facade\Log;
use app\model\AdminSchoolDevice;
use app\model\AdminSchoolRkeRecord;

/**
 * @Title: app\task\job$Demo
 * @author max
 * @date 2021年12月10日
 */
class SchoolRkeRecord{
    /**
     * 队列入口
     * @param Job $job
     * @param $data
     */
    public function fire(Job $job, $data)
    {
        $isJobDone = $this->handle($data);
        if ($isJobDone) {
            //如果任务执行成功，记得删除任务
            $job->delete();
        }else{
            //通过这个方法可以检查这个任务已经重试了几次了
            if ($job->attempts() > 3){
                Log::error('试了3次了');
                $job->delete();
            }
        }
    }

    /**
     * 处理
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($data)
    {
        //Log::error($data);
        $data['staff_id'] = empty($data['staff_id']) ? 0 : (int)$data['staff_id'];
        if(empty($data['serial']) || $data['staff_id']<=0){
            return false;
        }
        $deviceData = AdminSchoolDevice::getOneData($data['serial']);
        if(empty($deviceData['school_id'])){
            return false;
        }
        $staff = AdminStaff::where('id', '=', $data['staff_id'])->find();
        if (!$staff) {
            return false;
        }
        $insertData = [
            'school_id'=>$staff['school_id'],
            'serial'=>$data['serial'],
            'serial_type' => $deviceData['serial_type'],
            'door_location'=>$deviceData['door_location'],
            'card'=>$data['card'],
            'card_type'=>$data['card_type'],
            'card_name'=>$data['card_name'],
            'acs_res'=>$data['acs_res'],
            'act_index'=>$data['act_index'],
            'create_time'=>$data['time'],
            'staff_id' => $data['staff_id']
        ];
        if(!empty($data['face_similarity'])){
            $insertData['face_similarity'] = $data['face_similarity'];
        }
        $result = AdminSchoolRkeRecord::create($insertData);
        return (bool)$result;
    }
}